/**
 *
 * @author Wilson Santos, <wilson.santos@ua.pt>
 */
public class CSV2Plot {
  def static threadList = ["10", "30", "50", "70", "90"]
  def static cycleList = ["35", "65", "90"]
  def static folder = "images/results" + File.separator
  def static drivertypes = [
    "Leitura", "Actualização", "Inserção", "Remoção"
  ]
  def static cachetypes = [
    "10 ", "20", "50", "75", "100"
  ]
  def static drivertests = [
    ["MSJDBC", "CJDBC_I"],
    ["MSJDBC", "CJDBC_S"],
    ["MSJDBC", "WJDBC"],
    ["WJDBC", "CJDBC_S"],
    ["WJDBC", "CJDBC_I"]
  ]
  def static cachetests = [
    ["CJDBC_I", "CJDBC_SM"]
  ]

  def static times = [
    'ExecT', 'SetupT', 'Total'
  ]
  
  public static void main(String[] args) {
    File dir = new File(folder)
    if(!dir.exists()) {
      dir.mkdir()
    }
    
    println "Creating MSJDBC plots..."
    csv2plot("jdbccmp", drivertests, drivertypes)

    println "Creating CacheTest plots..."
    csv2plot("cachecmp", cachetests, cachetypes)
    csv2plot("cachecmp", [["CJDBC_I", "CJDBC_S"]], ["100"])

    println "Creating MSJDBC Column Delay plots..."
    csv2plot_delay("delayccmp", drivertests, drivertypes[0..1], 1)    

    println "Creating MSJDBC Line Delay plots..."
    csv2plot_delay("delaylcmp", drivertests, drivertypes[0..1], 8) 
  }
  
  def static getName(first, second) {
    first + "/" + second
  }

  def static getFileName(prefix, op, first, second) {
    "${prefix}-${first}-${second}-${op}"
  }

  def static convchars(name) {
    name.replaceAll("ã", "a").replaceAll("ç", "c").replaceAll(" ", "")
  }

  def static csv2plot(cmp, ratios, contextList) {
    getThreadList()
    getCycleList()

    contextList.each { context ->
      def convcontext = convchars(context)
      ratios.each { it ->
        createGnu(cmp, convcontext, it[0], it[1], times[0], 2)
        createGnu(cmp, convcontext, it[0], it[1], times[1], 3)
        createGnu(cmp, convcontext, it[0], it[1], times[2], 4)

        createTex(cmp, context, it[0], it[1], times[0], times[1], times[2])
      }
    }
  }

  def static csv2plot_delay(cmp, ratios, contextList, delay) {
    getThreadList()
    getCycleList()

    contextList.each { context ->
      def convcontext = convchars(context)
      ratios.each { it ->
        createGnu(cmp, convcontext, it[0], it[1], times[0], 2)

        createTexForDelay(cmp, context, it[0], it[1], delay)
      }
    }
  }

  def static createGnu(prefix, type, first, second, time, tIdx) {
    String filename = getFileName(prefix, type, first, second)
    File file = new File("${folder}${filename}-${time}.gnu")
    String content = """\
    set size ratio 1.1
    set datafile separator ";"
    set xtics (${xtics()})
    set grid
#    set key below width 0.8
    set key top left
    set terminal post enh #color
    set out '${filename}-${time}.eps'

#    set title '${time}'
    set title '${getName(first, second)}' 2 # 2==x-offset
    set xlabel 'quantidade de threads'
#    set ylabel '${getName(first, second)}' 2 # 2==x-offset
    
    plot "../csv/${filename}.csv" index 0 u 1:${tIdx} w lp lw 3 title "${cycleList.get(0)} linhas/thread" """
    cycleList.subList(1, cycleList.size()).eachWithIndex { it, idx ->
      content = content.concat(", \"\" index ${idx + 1} u 1:${tIdx} w lp lw 3 title \"${it} linhas/thread\"")
    }

    file.write(content)
  }

  def static createTex(cmp, context, first, second, time1, time2, time3) {
    def plotsize = "width=.3333333333333333333\\textwidth"
    String filename = getFileName(cmp, convchars(context), first, second)
    File file = new File("${folder}${filename}.tex")
    String content = """\
\\begin{figure}[hb!t]
  \\centering
  \\caption[\$${first}/${second}\$, no contexto {\\bf ${context}}.]{Comparação entre \$${first}\$ e \$${second}\$, no contexto {\\bf ${context}}.}
  \\label{fig:${filename}}
  \\subfloat[${time1}]{\\includegraphics[angle=-90,${plotsize}]{images/results/${filename}-${time1}}}
  \\subfloat[${time2}]{\\includegraphics[angle=-90,${plotsize}]{images/results/${filename}-${time2}}}
  \\subfloat[${time3}]{\\includegraphics[angle=-90,${plotsize}]{images/results/${filename}-${time3}}}
\\end{figure}
    """
    file.write(content, "utf-8")
  }
  
  def static createTexForDelay(cmp, context, first, second, delay) {
    def plotsize = "width=6cm"
    String filename = getFileName(cmp, convchars(context), first, second)
    File file = new File("${folder}${filename}.tex")
    String content = """\
\\begin{figure}[hb!t]
  \\centering
  \\caption[\$${first}/${second}\$, efeito do atraso no contexto {\\bf ${context}}.]{Efeito do atraso na comparação entre \$${first}\$ e \$${second}\$, no contexto {\\bf ${context}}.}
  \\label{fig:${filename}}
  \\subfloat[Sem atraso]{\\includegraphics[angle=-90,${plotsize}]{images/results/${filename.replaceFirst(cmp, "jdbccmp")}-ExecT}}
  \\subfloat[Atraso de ${delay}ms]{\\includegraphics[angle=-90,${plotsize}]{images/results/${filename}-ExecT}}
\\end{figure}
    """
    file.write(content, "utf-8")
  }

  def static xtics() {
    String ret = ""
    threadList.each {
      ret += "\"${it}\" ${it}, "
    }
    ret.substring(0, ret.length() - 2)
  }
}
